package com.kuyou.publiclibrary.utils;

import java.util.List;

public class ByteUtils {
    public static int byteToInt(byte b) {
        //Java的byte是有符号，通过 &0xFF转为无符号
        return b & 0xFF;
    }

    public static String bytesToHex(byte[] bytes) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(bytes[i] & 0xFF);
            if (hex.length() < 2) {
                sb.append(0);
            }
//            sb.append(hex);
            sb.append(hex + " ");
        }
        return sb.toString();
    }


    public static String bytesToTowHex(List<Byte[]> bytes) {
        StringBuffer sb = new StringBuffer();
        for (Byte[] i : bytes) {
            String hex = Integer.toHexString(i[0] & 0xFF);

            if (hex.length() < 2) {
                sb.append(0);
            }
            sb.append(hex + " ");
//            sb.append(hex);
            String hes = Integer.toHexString(i[1] & 0xFF);
            if (hes.length() < 2) {
                sb.append(0);
            }
            sb.append(hes + " " + ",");
        }
        return sb.toString();
    }

    public static int bytesTwoData(String high, String low) {
        int raw = Integer.parseInt(high,16) * 256 + Integer.parseInt(low,16);
        if (raw >= 32768) {

            return raw - 65536;
        }
        return raw;
    }

    public static int bytesToIntForBP(byte high, byte low) {

        int raw = Integer.parseInt( Integer.toHexString(high & 0xFF),16) * 256 + Integer.parseInt( Integer.toHexString(low & 0xFF),16);
        if (raw >= 32768) {
            return raw - 65536;
        }

        return raw;
    }


    public static int bytesTowInt(byte high, byte low) {

        return (high << 8) | low;
    }
}
